package com.knight.mall.admin.controller.enterprise;

import java.io.IOException;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.knight.mall.admin.controller.BaseController;
import com.knight.mall.admin.page.model.EnterpriseAgent;
import com.knight.mall.admin.web.utils.MallApiResponse;
import com.knight.mall.admin.web.utils.MallrApiResponseCode;
import com.knight.mall.exception.ServiceException;
import com.knight.mall.model.Enterprise;
import com.knight.mall.model.Region;
import com.knight.mall.query.EnterpriseQuery;
import com.knight.mall.service.EnterpriseService;
import com.knight.mall.service.FileUploadService;
import com.knight.mall.service.RegionService;
import com.knight.mall.utils.DigestsUtils;
import com.knight.mall.utils.ValidateContentType;

@RequestMapping(value = "enterprise")
@Controller
public class EnterpriseController extends BaseController {

	@Autowired
	private FileUploadService fileUploadService;

	/**
	 * 获取商家id
	 * 
	 * @return
	 */
	public Long getId(HttpServletRequest request) {
		EnterpriseAgent enterpriseAgent = (EnterpriseAgent) request.getSession()
				.getAttribute(EnterpriseAgent.REQUEST_ATTR_NAME);

		if (enterpriseAgent == null) {
		}
		return enterpriseAgent.getId();
	}

	@Autowired
	private EnterpriseService enterpriseService;

	@Autowired
	private RegionService regionService;

	/**
	 * 查询商家信息
	 * 
	 * @return
	 * @throws ServiceException
	 */
	@RequestMapping(value = "info")
	public String info(Model model, HttpServletRequest request) throws ServiceException {

		List<Region> listProvince = regionService.getAllProvince();

		Enterprise e = enterpriseService.getById(getId(request));
		if (e != null) {
			model.addAttribute("e", e);

			String province = e.getProvince();
			String city = e.getCity();
			if (province != null && !"".equals(province) && city != null && !"".equals(city)) {
				for (Region r : listProvince) {
					if (r.getRegionName().equals(province)) {
						List<Region> listCity = regionService.getByParentCode(r.getCode());
						model.addAttribute("citys", listCity);
						for (Region c : listCity) {
							if (c.getRegionName().trim().equals(city.trim())) {
								List<Region> listRegion = regionService.getByParentCode(c.getCode());
								model.addAttribute("regions", listRegion);
							}
						}
						break;
					}
				}
			}
			if (e.getTelephone() != null && e.getTelephone().contains("-")) {
				model.addAttribute("areaCode", e.getTelephone().split("-")[0]);
				model.addAttribute("telePhoneNum", e.getTelephone().split("-")[1]);
			}
		}
		model.addAttribute("title", "商家信息");
		model.addAttribute("provinces", listProvince);
		return "enterpriseinfo";
	}

	/**
	 * 图片上传
	 * 
	 * @param files
	 * @param type
	 * @param response
	 * @return
	 * @throws IOException
	 * @throws ServiceException
	 */
	@RequestMapping(value = "fileUpload")
	@ResponseBody
	public MallApiResponse fileUpload(@RequestParam("file") MultipartFile[] files, HttpServletResponse response,
			HttpServletRequest request) throws IOException, ServiceException {

		if (files == null || files.length <= 0) {
			// 没有上传文件
			return MallApiResponse.create(MallrApiResponseCode._1000001.getCode(), "请选择文件!");
		}
		// 文件类型
		String contentType = files[0].getContentType();
		// 文件大小
		long fileSize = files[0].getSize();

		if (!ValidateContentType.validateImage(contentType)) {
			return MallApiResponse.create(MallrApiResponseCode._1000001.getCode(), "请上传图片!");
		}

		Map<String, String> map = fileUploadService.uploadFileReturnMap(getId(request), files[0].getInputStream());
		return MallApiResponse.create(map);
	}

	/**
	 * 保存商家信息
	 * 
	 * @throws ServiceException
	 */
	@RequestMapping(value = "save")
	@ResponseBody
	public MallApiResponse save(Enterprise e, HttpServletRequest request, String areaCode, String telePhoneNum)
			throws ServiceException {

		if (e.getEnterpiseName() == null || "".equals(e.getEnterpiseName())) {
			return MallApiResponse.create(MallrApiResponseCode._1000001.getCode(), "企业名称为空!");
		}
		if (e.getContactPhone() == null || "".equals(e.getContactPhone())) {
			return MallApiResponse.create(MallrApiResponseCode._1000001.getCode(), "联系人电话为空!");
		}

		if (e.getProvince() != null && !"".equals(e.getProvince())) {
			Region r = regionService.getByCode(e.getProvince());
			if (r != null) {
				String province = r.getRegionName();
				e.setProvince(province);
			}
		}
		if (e.getCity() != null && !"".equals(e.getCity())) {
			Region r = regionService.getByCode(e.getCity());
			if (r != null) {
				String city = r.getRegionName();
				e.setCity(city);
			}
		}
		if (e.getRegion() != null && !"".equals(e.getRegion())) {
			Region r = regionService.getByCode(e.getRegion());
			if (r != null) {
				String region = r.getRegionName();
				e.setRegion(region);
			}
		}

		if (areaCode != null && !"".equals(areaCode.trim()) && telePhoneNum != null
				&& !"".equals(telePhoneNum.trim())) {
			e.setTelephone(areaCode.trim() + "-" + telePhoneNum.trim());
		}

		e.setId(getId(request));
		e.setGmtModify(new Date());
		enterpriseService.update(e);
		return MallApiResponse.create();
	}

	/**
	 * 修改密码页面
	 */
	@RequestMapping(value = "updatePage")
	public String updatePage(Model model) {
		model.addAttribute("title", "修改密码");
		return "updatePass";
	}

	/**
	 * 修改密码
	 */
	@RequestMapping(value = "updatePass")
	@ResponseBody
	public MallApiResponse updatePass(String oldPass, String newPassOne, String newPassTwo, String random,
			String passSign, HttpServletRequest request) {

		if (oldPass == null || "".equals(oldPass)) {
			return MallApiResponse.create(MallrApiResponseCode._1000001.getCode(), "原始密码为空!");
		}
		if (newPassOne == null || "".equals(newPassOne)) {
			return MallApiResponse.create(MallrApiResponseCode._1000001.getCode(), "新密码为空!");
		}
		if (newPassTwo == null || "".equals(newPassTwo)) {
			return MallApiResponse.create(MallrApiResponseCode._1000001.getCode(), "确认密码为空!");
		}

		if (random == null || "".equals(random)) {
			return MallApiResponse.create(MallrApiResponseCode._1000001.getCode(), "请求数据有误!");
		}
		if (passSign == null || "".equals(passSign)) {
			return MallApiResponse.create(MallrApiResponseCode._1000001.getCode(), "请求数据有误!");
		}

		EnterpriseQuery query = new EnterpriseQuery();
		query.setIdArray(getId(request));
		List<Enterprise> list = enterpriseService.queryList(query);
		if (list != null && list.size() == 1) {
			Enterprise e = list.get(0);
			if (!e.getPassword().equals(oldPass)) {
				return MallApiResponse.create(MallrApiResponseCode._1000001.getCode(), "原始密码不正确!");
			}
		}
		if (!newPassOne.equals(newPassTwo)) {
			return MallApiResponse.create(MallrApiResponseCode._1000001.getCode(), "新密码和确认密码不相同!");
		}
		String newPassSign = DigestsUtils.md5Hex(DigestsUtils.md5Hex((newPassTwo + random).getBytes()).getBytes());

		if (!passSign.equals(newPassSign)) {
			return MallApiResponse.create(MallrApiResponseCode._1000001.getCode(), "非法请求!");
		}

		Enterprise e = new Enterprise();
		e.setId(getId(request));
		e.setPassword(newPassOne);
		e.setGmtModify(new Date());
		enterpriseService.update(e);
		return MallApiResponse.create();
	}

	/**
	 * 用户退出
	 * 
	 * @return
	 */
	@RequestMapping(value = "userLogout")
	public String userLogout(HttpServletRequest request, HttpServletResponse response) {
		// 清楚缓存中的数据
		// 删除cookie
		/*
		 * Cookie cookie = new Cookie("adminPass", null); cookie.setPath("/");
		 * cookie.setMaxAge(0); cookie = new Cookie("adminLogin", null);
		 * cookie.setPath("/"); cookie.setMaxAge(0);
		 */
		return "redirect:/";
	}

}
